AddCSLuaFile( "cl_init.lua" ) // Make sure clientside  
AddCSLuaFile( "shared.lua" )  // and shared scripts are sent.     
include('shared.lua')     

--setting up
function ENT:Initialize()  
	self.Entity:SetModel("models/props_lab/tpplugholder_single.mdl")  	
	self.Entity:PhysicsInit( SOLID_VPHYSICS )      // Make us work with physics,  	
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )   // after all, gmod is a physics  	
	self.Entity:SetSolid( SOLID_VPHYSICS )         // Toolbox                
	local phys = self.Entity:GetPhysicsObject()  	
	if (phys:IsValid()) then  		
		phys:Wake()  	
	end  
	self.ConnectDistance = 300
	if ( RES_DISTRIB == 1 ) then
		RD_AddResource(self.Entity, "energy", 0)
		RD_AddResource(self.Entity, "air", 0)
		RD_AddResource(self.Entity, "coolant", 0)
		RD_AddResource(self.Entity, "hydrogen", 0)
	end
		
end     

--spawnit!
function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end

	local SpawnPos = tr.HitPos + tr.HitNormal * 16

	local ent = ents.Create( "sent_backpack_dockingstation" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Use(activator)
end
  
function ENT:Think()
	local backpacks = ents.FindByClass("sent_backpack_lifesupport")
	for k,v in pairs(backpacks) do
		local link = true
		if self.Entity:GetPos():Distance(v:GetPos()) <= self.ConnectDistance then
			for _, rtype in pairs( self.Entity:GetTable().resources ) do
				for _, check in pairs( rtype.links ) do
					if (v == check.ent) then
						link = false
					end
				end
			end
			if link then
				Dev_Link(self.Entity, v, Vector(5,13,10), Vector(0,0,25), "cable/cable2", Color(255,255,255,255), 5)
			end
		else
			for _, rtype in pairs( self.Entity:GetTable().resources ) do
				for _, check in pairs( rtype.links ) do
					if (v == check.ent) then
						Dev_Unlink(self.Entity, v)
					end
				end
			end
		end
	end
end

function ENT:OnRemove()
	if (RES_DISTRIB == 1) then Dev_Unlink_All(self.Entity) end
end
